<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import API from '@/services';

// todo: 关于这些后面会抽象成 一个 API-Select 这些会 通过 API-Select 扩展

// todo: 考虑支持 multiple
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
});
const emit = defineEmits(['update:modelValue']);

const options = ref<any[]>([]);
const value = ref();
const loading = ref(false);
const remoteMethod = async (query: any) => {
  // if (query !== '') {
  loading.value = true;
  const { data } = await API.userInfoService.getUser({
    name: query
  });
  loading.value = false;
  options.value =
    data?.map((d) => {
      return {
        label: `${d.label}`,
        value: `${d.value}`
      };
    }) || [];
  // } else {
  //   options.value = [];
  // }
};
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== value.value) {
      value.value = newVal || '';
    }
  }
);
watch(value, (newVal, preVal) => {
  if (newVal !== preVal) {
    emit('update:modelValue', newVal);
  }
});

onMounted(() => {
  remoteMethod('');
});
</script>
<template>
  <ASelect
    v-model="value"
    style="width: 100%"
    allow-search
    @search="remoteMethod"
    allow-clear
    :options="options"
    :loading="loading"
    placeholder="请输入"
  />
</template>
